package io.github.xxyopen.novel.app.chatmemory;


import io.github.xxyopen.novel.app.utils.MessageConvertUtil;
import io.github.xxyopen.novel.core.auth.UserHolder;
import io.github.xxyopen.novel.dao.entity.AiChatMemory;
import io.github.xxyopen.novel.service.AiChatMemoryService;
import org.jetbrains.annotations.NotNull;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Component
public class InMysqlChatMemory implements ChatMemory {

    @Autowired
    AiChatMemoryService aiChatMemoryService;

    @Override
    public void add(@NotNull String conversationId, @NotNull List<Message> messages) {
        if(conversationId.isEmpty()){
            throw new IllegalArgumentException("conversationId is null or empty");
        }
        String[] split = conversationId.split("\\.");
        conversationId = split[0];
        Long userId = Long.parseLong(split[1]);
        List<AiChatMemory> newMessage = new ArrayList<>();
        @NotNull String finalConversationId = conversationId;
        messages.forEach(message -> {
            AiChatMemory aiChatMemory = MessageConvertUtil.toAiChatMemory(message, finalConversationId,userId);
            newMessage.add(aiChatMemory);
        });
        aiChatMemoryService.saveBatch(newMessage);
    }

    @Override
    public @NotNull List<Message> get(String conversationId) {
        if(conversationId.isEmpty()){
            throw new IllegalArgumentException("conversationId is null or empty");
        }
        String[] split = conversationId.split("\\.");
        conversationId = split[0];
        Long userId = Long.parseLong(split[1]);

        return aiChatMemoryService.lambdaQuery()
                .eq(AiChatMemory::getConversationId, conversationId)
                .eq(AiChatMemory::getUserId, userId)
                .orderByDesc(AiChatMemory::getCreateTime)
                .last("limit " + 10)
                .list()
                .stream()
                .map(MessageConvertUtil::toMessage)
                .collect(Collectors.toList());
    }

    @Override
    public void clear(@NotNull String conversationId) {
        if(conversationId.isEmpty()){
            throw new IllegalArgumentException("conversationId is null or empty");
        }
        aiChatMemoryService.lambdaUpdate().eq(AiChatMemory::getConversationId, conversationId).remove();
    }
}
